package com.intelligent.eayon.handler;

import com.google.common.collect.Lists;
import com.intelligent.eayon.dto.AttrDto;
import com.intelligent.eayon.dto.RequestDto;
import com.intelligent.eayon.dto.ResponseDto;
import com.intelligent.eayon.message.Request;
import com.intelligent.eayon.message.Response;
import com.intelligent.eayon.message.TransMessage;
import com.intelligent.eayon.utils.AppConstant;
import com.intelligent.eayon.utils.MessageUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class SignUpClientHandler extends ChannelInboundHandlerAdapter {

    public static final Logger logger = LoggerFactory.getLogger(SignUpClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws UnsupportedEncodingException {

        RequestDto requestDto = new RequestDto();
        requestDto.setCode(AppConstant.REQ_SIGN);

        List<AttrDto> attrDtoList = Lists.newArrayList();
        AttrDto attrDto1 = new AttrDto();
        attrDto1.setEqlg(12);
        attrDto1.setEqid("169.254.1.1");

        attrDtoList.add(attrDto1);

        requestDto.setAttr(attrDtoList);
        requestDto.setAtlg(MessageUtils.attrListLength(attrDtoList));

        Request request = MessageUtils.requestDtoEncoder(requestDto);
        TransMessage transMessage = MessageUtils.buildTransMessage(null, request);

        ctx.writeAndFlush(transMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        TransMessage transMessage = (TransMessage) msg;
        Response response = MessageUtils.responseDecoder(transMessage.getBody().getData());
        ResponseDto responseCKDto = MessageUtils.responseDtoDecoder(response);

        logger.info("Receive msg" + responseCKDto);
    }
}
